﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using System.Web.Security;
using CashFlow.Common;

namespace CashFlow.Entities
{
	public class AppIdentity : IIdentity
	{
		private FormsAuthenticationTicket ticket;
		private string friendlyName;
		private static List<string> ProviderKeys;
		private string tenantId;


		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="T:AppIdentity"/> class.
		/// </summary>
		static AppIdentity()
		{
			ProviderKeys = new List<string>(12) 
			{ 
				"google",
				"yahoo",
				"aol",
				"myopenid",
				"livejournal",
				"flickr",
				"technorati",
				"wordpress",
				"blogspot",
				"verisignlabs",
				"launchpad",
				"claimid"
			};
		}

		public AppIdentity(FormsAuthenticationTicket ticket)
		{
			this.ticket = ticket;
			this.tenantId = ticket.Name;
			this.friendlyName = ticket.UserData;
			//IdentifyProvider();
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:AppIdentity"/> class.
		/// </summary>
		public AppIdentity(string claimedIdentifier)
		{
			ClaimedIdentifier = claimedIdentifier;
			IdentifyProvider();
		}
		#endregion

		#region Properties

		/// <summary>
		/// Gets or sets the ClaimedIdentifier.
		/// </summary>
		/// <value>The OpenAuth ClaimedIdentifier.</value>
		public string ClaimedIdentifier
		{
			get;
			set;
		}

		public string AuthenticationType
		{
			get { return "CF"; }
		}

		public bool IsAuthenticated
		{
			get { return true; }
		}

		public string Name
		{
			get { return tenantId; }
		}

		public string EncodedIdentifier
		{
			get 
			{ 
				return FormsAuthentication.HashPasswordForStoringInConfigFile(
					ClaimedIdentifier, 
					"MD5"); 
			}
		}


		public string FriendlyName
		{
			set
			{
				friendlyName = string.IsNullOrEmpty(value) ? "Friend" : value;
			}
			get
			{
				return friendlyName;
			}
		}

		/// <summary>
		/// Gets or sets the provider.
		/// </summary>
		/// <value>The provider.</value>
		public string Provider
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets the tenant id.
		/// </summary>
		/// <value>The tenant id.</value>
		public string TenantId
		{
			get
			{
				return tenantId;
			}
			set
			{
				tenantId = value;
			}
		}
		#endregion

		private void IdentifyProvider()
		{
			Provider = ProviderKeys.FirstOrDefault(k => ClaimedIdentifier.Contains(k));
			if (Provider == null)
			{
				Provider = "unkown";
				//TODO: vvs p3 log event that provider was not identified.
			}
		}

	}
}